
package com.eworking.eim.group;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import com.eworking.eim.database.EIMDatabaseManager;
import com.eworking.eim.database.EIMDatabaseTable;
import com.eworking.eim.util.EIMLog;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class EIMGroupTable implements EIMDatabaseTable {
    
    /** 日志输出标记 */
    private static final String _TAG = EIMGroupTable.class.getSimpleName();
    
    /** 表名 */
    private static final String _TABLE_NAME = "IM_GROUP";
    
    /** 数据库管理 */
    private EIMDatabaseManager databaseManager = null;
    
    private static EIMGroupTable groupTable = null;
    
    public EIMGroupTable(EIMDatabaseManager databaseManager) {
        this.databaseManager = databaseManager;
        groupTable = this;
    }
    
    public static EIMGroupTable getInstance() {
        return groupTable;
    }
    
    /**
     * 保存群组信息
     * 
     * @param group 群组信息对象
     */
    public void insertGroup(EIMGroup group) {
        try {
            SQLiteDatabase database = this.databaseManager.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(Fields._GROUP_NAME, group.getGroupId());
            values.put(Fields._GROUP_JID, group.getJID());
            values.put(Fields._GROUP_NICK, group.getNickname());
            values.put(Fields._GROUP_OWNER, group.getOwner());
            values.put(Fields._GROUP_MODIFIED_TIME, group.getLastModifiedTime());
            values.put(Fields._GROUP_DESC, group.getDescription());
            values.put(Fields._GROUP_PUBLIC, group.isPublic());
            // 群组成员，以,分隔
            List<String> lstMembers = group.getMembers();
            String strMembers = this.convertListToString(lstMembers);
            values.put(Fields._GROUP_MEMBERS, strMembers);
            // 插入数据库
            database.insert(_TABLE_NAME, null, values);
        } catch (Exception e) {
            EIMLog.e(_TAG, "保存群组信息出错：" + e.getMessage());
        }
    }
    
    /**
     * 查询所有群组信息
     * 
     * @return Map<String, EIMGroup>
     */
    public Map<String, EIMGroup> queryAllGroup() {
        Map<String, EIMGroup> groupMap = new Hashtable<String, EIMGroup>();
        try {
            SQLiteDatabase database = this.databaseManager.getReadableDatabase();
            String sql = "SELECT * FROM " + _TABLE_NAME;
            Cursor cursor = database.rawQuery(sql, new String[0]);
            if (!(cursor.moveToFirst())) {
                cursor.close();
                return groupMap;
            }
            do {
                EIMGroup group = this.convertGroupFromCursor(cursor);
                groupMap.put(group.getGroupId(), group);
            } while (cursor.moveToNext());
            EIMLog.d(_TAG, "获取所有群组信息：" + groupMap.size());
            cursor.close();
        } catch (Exception e) {
            EIMLog.e(_TAG, "获取所有群组信息失败：" + e.getMessage());
        }
        return groupMap;
    }
    
    /**
     * 根据群组名称获取群组信息
     * 
     * @param groupName 群组名称
     * @return EIMGroup 群组信息
     */
    public EIMGroup queryGroupByGroupName(String groupName) {
        EIMGroup group = null;
        try {
            SQLiteDatabase database = this.databaseManager.getReadableDatabase();
            String sql = "SELECT * FROM " + _TABLE_NAME + " WHERE " + Fields._GROUP_NAME + " = ? ";
            Cursor cursor = database.rawQuery(sql, new String[] { groupName });
            if (cursor != null) {
                if (cursor.moveToFirst())
                    group = this.convertGroupFromCursor(cursor);
                cursor.close();
            }
            EIMLog.d(_TAG, "获取群组信息：" + group.getGroupId());
        } catch (Exception e) {
            EIMLog.e(_TAG, "获取群组信息失败," + groupName + " ：" + e.getMessage());
        }
        return group;
    }
    
    /**
     * 更新群组信息
     * 
     * @param group 群组信息
     */
    public void updateGroup(EIMGroup group) {
        try {
            SQLiteDatabase database = this.databaseManager.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(Fields._GROUP_NAME, group.getGroupId());
            values.put(Fields._GROUP_JID, group.getJID());
            values.put(Fields._GROUP_NICK, group.getNickname());
            values.put(Fields._GROUP_OWNER, group.getOwner());
            values.put(Fields._GROUP_MODIFIED_TIME, group.getLastModifiedTime());
            values.put(Fields._GROUP_PUBLIC, group.isPublic());
            values.put(Fields._GROUP_DESC, group.getDescription());
            // 群组成员
            String strMembers = this.convertListToString(group.getMembers());
            values.put(Fields._GROUP_MEMBERS, strMembers);
            // 更新群组信息
            database.update(_TABLE_NAME, values, Fields._GROUP_NAME + " = ? ", new String[] { group.getGroupName() });
            EIMLog.d(_TAG, "删除群组信息" + group.toString());
        } catch (Exception e) {
            EIMLog.e(_TAG, "更新群组信息失败," + group.getGroupName() + " ：" + e.getMessage());
        }
    }
    
    /**
     * 根据群组名称删除群组信息
     * 
     * @param groupName 群组名称
     */
    public void deleteGroup(String groupName) {
        try {
            SQLiteDatabase database = this.databaseManager.getWritableDatabase();
            database.delete(_TABLE_NAME, Fields._GROUP_NAME + " = ? ", new String[] { groupName });
            EIMLog.d(_TAG, "删除群组信息" + groupName);
        } catch (Exception e) {
            EIMLog.e(_TAG, "删除群组信息失败," + groupName + " ：" + e.getMessage());
        }
    }
    
    /**
     * 返回Group群组信息对象
     * 
     * @param cursor
     * @return
     */
    private EIMGroup convertGroupFromCursor(Cursor cursor) {
        String groupName = cursor.getString(cursor.getColumnIndex(Fields._GROUP_NAME));
        EIMGroup group = new EIMGroup(groupName);
        group.setJID(cursor.getString(cursor.getColumnIndex(Fields._GROUP_JID)));
        group.setGroupName(cursor.getString(cursor.getColumnIndex(Fields._GROUP_NICK)));
        group.setOwner(cursor.getString(cursor.getColumnIndex(Fields._GROUP_OWNER)));
        group.setLastModifiedTime(cursor.getInt(cursor.getColumnIndex(Fields._GROUP_MODIFIED_TIME)));
        group.setPublic(cursor.getInt(cursor.getColumnIndex(Fields._GROUP_PUBLIC)) != 0);
        group.setDescription(cursor.getString(cursor.getColumnIndex(Fields._GROUP_DESC)));
        // 群组成员
        String strMembers = cursor.getString(cursor.getColumnIndex(Fields._GROUP_MEMBERS));
        StringTokenizer tokenizer = new StringTokenizer(strMembers, ",");
        while (tokenizer.hasMoreTokens()) {
            group.addMember(tokenizer.nextToken());
        }
        return group;
    }
    
    /**
     * 将list转换为String，以,分割
     * 
     * @param listData List<String>
     * @return
     */
    private String convertListToString(List<String> listData) {
        StringBuffer sb = new StringBuffer(512);
        for (String data : listData) {
            sb.append(data).append(",");
        }
        return sb.toString();
    }
    
    @Override
    public void onCreated(SQLiteDatabase database) {
        // 创建表语句
        String sql =
            "CREATE TABLE " + _TABLE_NAME + " ( " + Fields._GROUP_NAME + " TEXT PRIMARY KEY , " + Fields._GROUP_JID
                + " TEXT NOT NULL , " + Fields._GROUP_NICK + " TEXT NOT NULL , " + Fields._GROUP_OWNER
                + " TEXT NOT NULL , " + Fields._GROUP_MODIFIED_TIME + " INTEGER , " + Fields._GROUP_PUBLIC
                + " INTEGER , " + Fields._GROUP_DESC + " TEXT , " + Fields._GROUP_MEMBERS + " TEXT );";
        database.execSQL(sql);
    }
    
    @Override
    public void onDroped(SQLiteDatabase database) {
        // 删除表语句
        String sql = "DROP TABLE IF EXISTS " + _TABLE_NAME;
        database.execSQL(sql);
    }
    
    private static final class Fields {
        
        /** 群组名称 */
        public static final String _GROUP_NAME = "name";
        
        /** 群组昵称 */
        public static final String _GROUP_NICK = "nick";
        
        /** 群组备注 */
        public static final String _GROUP_DESC = "desc";
        
        /** 群组拥有者 */
        public static final String _GROUP_OWNER = "owner";
        
        /** 群组成员 */
        public static final String _GROUP_MEMBERS = "members";
        
        /** 最后修改时间 */
        public static final String _GROUP_MODIFIED_TIME = "modified_time";
        
        /** 群组JID */
        public static final String _GROUP_JID = "jid";
        
        /** 是否公开 */
        public static final String _GROUP_PUBLIC = "ispublic";
    }
}
